<template>
  <div class="container">
    <h1>Electron UDP 通信诊断工具</h1>

    <div class="status-bar" :class="statusClass">
      <span v-if="socketStatus === 'bound'">
        <i class="status-icon connected"></i> 已绑定到 {{ boundAddress }}:{{ boundPort }}
      </span>
      <span v-else-if="socketStatus === 'error'">
        <i class="status-icon error"></i> {{ statusMessage }}
      </span>
      <span v-else> <i class="status-icon disconnected"></i> 未绑定 </span>
    </div>

    <div class="control-panel">
      <div class="panel-section">
        <h2>网络配置</h2>

        <div class="form-group">
          <label>网络接口:</label>
          <select v-model="selectedInterface" @change="changeInterface">
            <option v-for="(iface, index) in networkInterfaces" :key="index" :value="iface.address">
              {{ iface.name }} ({{ iface.address }}) - 广播地址: {{ iface.broadcast }}
            </option>
          </select>
        </div>

        <div class="form-group">
          <label>本地端口:</label>
          <input v-model="localPort" type="number" placeholder="默认4125" />
          <button @click="updatePort">更新端口</button>
        </div>

        <div class="form-group">
          <button @click="rescanNetworks"><i class="icon refresh"></i> 重新扫描网络接口</button>
          <button @click="testBroadcast"><i class="icon broadcast"></i> 发送测试广播</button>
        </div>
      </div>

      <div class="panel-section">
        <h2>消息发送</h2>

        <div class="form-group">
          <label>目标IP:</label>
          <input v-model="targetIp" placeholder="255.255.255.255" />
        </div>

        <div class="form-group">
          <label>目标端口:</label>
          <input v-model="targetPort" type="number" placeholder="4125" />
        </div>

        <div class="form-group">
          <label>消息内容:</label>
          <textarea v-model="message" placeholder="输入要发送的消息"></textarea>
        </div>

        <div class="button-group">
          <button class="primary" @click="sendMessage">
            <i class="icon send"></i> 发送定向消息
          </button>
          <button class="secondary" @click="sendBroadcast">
            <i class="icon broadcast"></i> 发送广播消息
          </button>
        </div>
      </div>
    </div>

    <div class="message-container">
      <h2>
        消息日志
        <span class="badge">{{ receivedMessages.length }}</span>
        <button class="clear-btn" @click="receivedMessages = []">
          <i class="icon clear"></i> 清空
        </button>
      </h2>
      <div ref="messageList" class="message-list">
        <div
          v-for="(msg, index) in receivedMessages"
          :key="index"
          class="message"
          :class="msg.type"
        >
          <div class="message-header">
            <span class="from">
              <span v-if="msg.type === 'sent'">发送到</span>
              <span v-else>来自</span>
              {{ msg.from.ip }}:{{ msg.from.port }}
            </span>
            <span class="time">{{ formatTime(msg.timestamp) }}</span>
          </div>
          <div class="message-content">{{ msg.message }}</div>
        </div>

        <div v-if="receivedMessages.length === 0" class="empty-state">
          <i class="icon message"></i>
          <p>没有消息记录</p>
          <p>尝试发送一条消息或广播</p>
        </div>
      </div>
    </div>

    <div class="troubleshooting">
      <h2>故障排除</h2>
      <div class="tips">
        <div class="tip">
          <h3><i class="icon firewall"></i> 防火墙设置</h3>
          <p>确保防火墙允许UDP端口 {{ localPort }} 的通信</p>
        </div>
        <div class="tip">
          <h3><i class="icon network"></i> 网络隔离</h3>
          <p>检查设备是否在同一局域网内，公共WiFi可能隔离设备</p>
        </div>
        <div class="tip">
          <h3><i class="icon interface"></i> 网卡选择</h3>
          <p>如果你有多个网络接口，请选择正确的接口进行绑定</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'

export default {
  setup() {
    const localPort = ref('4125')
    const targetIp = ref('255.255.255.255')
    const targetPort = ref('4125')
    const message = ref('')
    const receivedMessages = ref([])
    const networkInterfaces = ref([])
    const selectedInterface = ref('')
    const socketStatus = ref('idle')
    const statusMessage = ref('')
    const boundAddress = ref('')
    const boundPort = ref('')

    const messageList = ref(null)

    // 计算状态栏样式
    const statusClass = ref('')

    // 格式化时间
    const formatTime = isoString => {
      return new Date(isoString).toLocaleTimeString()
    }

    // 更新端口
    const updatePort = () => {
      window.ipcRenderer.send('update-port', parseInt(localPort.value))
    }

    // 重新扫描网络接口
    const rescanNetworks = () => {
      window.ipcRenderer.invoke('rescan-networks')
    }

    // 更改网络接口
    const changeInterface = () => {
      window.ipcRenderer.invoke('change-interface', selectedInterface.value)
    }

    // 发送测试广播
    const testBroadcast = () => {
      message.value = '这是一个测试广播消息'
      sendBroadcast()
    }

    // 发送定向消息
    const sendMessage = () => {
      if (!message.value.trim()) return

      window.ipcRenderer.invoke('send-udp-message', {
        message: message.value,
        address: targetIp.value,
        port: parseInt(targetPort.value)
      })

      message.value = ''
    }

    // 发送广播消息
    const sendBroadcast = () => {
      if (!message.value.trim()) return

      window.ipcRenderer.invoke('send-broadcast', message.value)
      message.value = ''
    }

    // 处理接收到的UDP消息
    const handleUDPMessage = (event, data) => {
      receivedMessages.value.push(data)
      scrollToBottom()
    }

    // 处理网络接口信息
    const handleNetworkInterfaces = (event, interfaces) => {
      networkInterfaces.value = interfaces
      if (interfaces.length > 0) {
        selectedInterface.value = interfaces[0].address
      }
    }

    // 处理UDP状态
    const handleUDPStatus = (event, status) => {
      socketStatus.value = status.status
      boundAddress.value = status.address
      boundPort.value = status.port

      if (status.status === 'bound') {
        statusClass.value = 'connected'
        statusMessage.value = `已绑定到 ${status.address}:${status.port}`
      } else {
        statusClass.value = 'disconnected'
      }
    }

    // 处理错误
    const handleUDPError = (event, error) => {
      socketStatus.value = 'error'
      statusClass.value = 'error'
      statusMessage.value = error

      // 添加到消息列表
      receivedMessages.value.push({
        message: `[错误] ${error}`,
        from: { ip: '系统', port: 0 },
        timestamp: new Date().toISOString(),
        type: 'error'
      })

      scrollToBottom()
    }

    // 滚动到底部
    const scrollToBottom = () => {
      nextTick(() => {
        if (messageList.value) {
          messageList.value.scrollTop = messageList.value.scrollHeight
        }
      })
    }

    // 生命周期钩子
    onMounted(() => {
      window.ipcRenderer.on('udp-message', handleUDPMessage)
      window.ipcRenderer.on('udp-error', handleUDPError)
      window.ipcRenderer.on('network-interfaces', handleNetworkInterfaces)
      window.ipcRenderer.on('udp-status', handleUDPStatus)

      // 请求网络接口信息
      window.ipcRenderer.send('request-interfaces')

      // 添加初始提示消息
      receivedMessages.value.push({
        message: '应用程序已启动，等待消息...',
        from: { ip: '系统', port: 0 },
        timestamp: new Date().toISOString(),
        type: 'info'
      })
    })

    onUnmounted(() => {
      window.ipcRenderer.removeListener('udp-message', handleUDPMessage)
      window.ipcRenderer.removeListener('udp-error', handleUDPError)
      window.ipcRenderer.removeListener('network-interfaces', handleNetworkInterfaces)
      window.ipcRenderer.removeListener('udp-status', handleUDPStatus)
    })

    return {
      localPort,
      targetIp,
      targetPort,
      message,
      receivedMessages,
      networkInterfaces,
      selectedInterface,
      socketStatus,
      statusMessage,
      boundAddress,
      boundPort,
      statusClass,
      messageList,
      formatTime,
      updatePort,
      rescanNetworks,
      changeInterface,
      testBroadcast,
      sendMessage,
      sendBroadcast
    }
  }
}
</script>

<style scoped>
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background-color: #f0f2f5;
  color: #333;
  line-height: 1.6;
  padding: 20px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
  overflow-y: auto;
  height: calc(100vh - 80px);
}

h1 {
  background: linear-gradient(135deg, #4a90e2, #5e60ce);
  color: white;
  padding: 20px;
  text-align: center;
  font-size: 1.8rem;
  margin: 0;
}

.status-bar {
  padding: 12px 20px;
  text-align: center;
  font-weight: bold;
  font-size: 1.1rem;
}

.status-bar.connected {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.status-bar.error {
  background-color: #ffebee;
  color: #c62828;
}

.status-bar.disconnected {
  background-color: #fff3e0;
  color: #ef6c00;
}

.status-icon {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 8px;
}

.status-icon.connected {
  background-color: #4caf50;
}

.status-icon.disconnected {
  background-color: #ff9800;
}

.status-icon.error {
  background-color: #f44336;
}

.control-panel {
  display: flex;
  padding: 20px;
  gap: 20px;
  border-bottom: 1px solid #eee;
}

.panel-section {
  flex: 1;
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.panel-section h2 {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ddd;
  color: #4a90e2;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #555;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.3s;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  border-color: #4a90e2;
  outline: none;
  box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.2);
}

.form-group textarea {
  height: 100px;
  resize: vertical;
}

.button-group {
  display: flex;
  gap: 12px;
  margin-top: 10px;
}

button {
  padding: 12px 18px;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
}

button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

button:active {
  transform: translateY(0);
}

button.primary {
  background: linear-gradient(135deg, #4a90e2, #5e60ce);
  color: white;
}

button.secondary {
  background: linear-gradient(135deg, #36d1dc, #5b86e5);
  color: white;
}

button .icon {
  font-size: 1.2rem;
}

.message-container {
  padding: 20px;
}

.message-container h2 {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
  color: #4a90e2;
}

.badge {
  background-color: #4a90e2;
  color: white;
  border-radius: 12px;
  padding: 2px 8px;
  font-size: 0.9rem;
}

.clear-btn {
  background-color: #f5f5f5;
  color: #666;
  padding: 5px 10px;
  font-size: 0.9rem;
  margin-left: auto;
}

.message-list {
  height: 300px;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 15px;
  overflow-y: auto;
  background-color: #fafafa;
}

.message {
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message.sent {
  background-color: #e3f2fd;
  border-left: 4px solid #2196f3;
}

.message.received {
  background-color: #e8f5e9;
  border-left: 4px solid #4caf50;
}

.message.error {
  background-color: #ffebee;
  border-left: 4px solid #f44336;
}

.message.info {
  background-color: #fff3e0;
  border-left: 4px solid #ff9800;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 0.9rem;
  color: #666;
}

.message-content {
  font-size: 1.1rem;
  white-space: pre-wrap;
  word-break: break-word;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #777;
}

.empty-state .icon {
  font-size: 3rem;
  margin-bottom: 15px;
  color: #bdbdbd;
}

.troubleshooting {
  padding: 20px;
  background-color: #f9f9f9;
  border-top: 1px solid #eee;
}

.troubleshooting h2 {
  margin-bottom: 20px;
  color: #4a90e2;
}

.tips {
  display: flex;
  gap: 20px;
}

.tip {
  flex: 1;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.tip h3 {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  color: #333;
}

.tip .icon {
  color: #4a90e2;
  font-size: 1.5rem;
}

.tip p {
  color: #666;
  line-height: 1.5;
}
</style>
